﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.Composition;
using System.Data.Objects;
using System.Windows;
using MediaAssistant.Controls.Dialog;
using MediaAssistant.Controls.SplashScreen;
using MediaAssistant.Controls.WaitScreen;
using MediaAssistant.Data;
using MediaAssistant.Helper;
using MediaAssistant.Management;
using MefBasic;
using MefBasic.Commans;
using MediaAssistant.DAL;
using MediaAssistant.DAL.Helper;
using System.Linq;

namespace MediaAssistant.Controls.ProfileSelector
{
    [Export]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class ProfileSelectorPresenter : APresenter<ProfileSelectorView>, IDialogContentPresenter
    {
        [ImportingConstructor]
        public ProfileSelectorPresenter(ProfileSelectorView view) : base(view)
        {
            AddFolderCommand = new DelegateCommand(ExecuteAddFolderCommand);
            ChangeScanOptionCommand = new DelegateCommand(ExecuteChangeScanOption);
            DeleteScanFolderCommand = new DelegateCommand(ExecuteDeleteScanFolder);
        }

        public DelegateCommand DeleteScanFolderCommand { get; set; }

        private void ExecuteDeleteScanFolder(object obj)
        {
            ScannedDirectories.Remove((ScannedDirectory) obj);
        }

        private void InitializeScanOption()
        {
            ScanOption = string.IsNullOrWhiteSpace(RegistryHelper.ScanOption) ? Constants.ScanOption.MyComputer : RegistryHelper.ScanOption;
        }

        public DelegateCommand ChangeScanOptionCommand { get; set; }

        private void ExecuteChangeScanOption(object obj)
        {
            ScanOption = (string) obj;
        }

        public DelegateCommand AddFolderCommand { get; set; }

        private void ExecuteAddFolderCommand(object obj)
        {
            var folder = SystemHelper.GetFolderPath(string.Empty);
            if(folder==null)
                return;
            if (ScannedDirectories.Any(d=>d.FullPath==folder))
                return;
            ScannedDirectories.Add(new ScannedDirectory { FullPath = folder, IsAddedByUser = true });
        }

        public string ProfileName
        {
            get { return (string)GetValue(ProfileNameProperty); }
            set { SetValue(ProfileNameProperty, value); }
        }

        public static readonly DependencyProperty ProfileNameProperty =
            DependencyProperty.Register("ProfileName", typeof(string), typeof(ProfileSelectorPresenter), new UIPropertyMetadata(string.Empty));


        [Import]
        public LibraryDataSource DataSource
        {
            get { return (LibraryDataSource)GetValue(DataSourceProperty); }
            set { SetValue(DataSourceProperty, value); }
        }

        public static readonly DependencyProperty DataSourceProperty =
            DependencyProperty.Register("DataSource", typeof(LibraryDataSource), typeof(ProfileSelectorPresenter), new UIPropertyMetadata(null, OnPropertyChanged));

        protected override void DoPropertyChanged(DependencyPropertyChangedEventArgs e)
        {
            switch (e.Property.Name)
            {
                case "DataSource":
                    ScannedDirectories = new ObservableCollection<ScannedDirectory>(DatabaseManager.Instance.GetScanDirectories());
                    break;
            }
        }

        #region Implementation of IDialogContentPresenter

        public bool OnClosing(DialogResult dialogResult)
        {
            if (dialogResult == DialogResult.Cancel)
                return true;
            if(string.IsNullOrWhiteSpace(ProfileName))
                return false;
            return true;
        }




        public string ScanOption
        {
            get { return (string)GetValue(ScanOptionProperty); }
            set { SetValue(ScanOptionProperty, value); }
        }

        public static readonly DependencyProperty ScanOptionProperty =
            DependencyProperty.Register("ScanOption", typeof(string), typeof(ProfileSelectorPresenter), new UIPropertyMetadata(null,OnPropertyChanged));

        #endregion

        public bool SelectProfile()
        {
            if (string.IsNullOrWhiteSpace(RegistryHelper.ProfileName)
                || string.IsNullOrWhiteSpace(RegistryHelper.ScanOption)
                || DatabaseManager.Instance.IsProfileExists(RegistryHelper.ProfileName)==false)
            {
                Splasher.Close();
                Logger.Instance.Write("Profile not found");
                var selectProfile = ChangeProfile();
                Resolve<WaitScreenPresenter>().Show();
                return selectProfile;
            }
            Logger.Instance.Write("Existing Profile Loaded");
            return true;
        }

        [Import]
        private IWaitScreenService WaitScreen { get; set; }
        public bool ChangeProfile()
        {
            ProfileName = RegistryHelper.ProfileName;
            InitializeScanOption();
            if (Resolve<IDialogPresenter>().ShowDialog("Select Profile", this) == DialogResult.Ok)
            {
                SaveProfile();
                DatabaseManager.Instance.SaveScannedFolders(ScannedDirectories);
                if (IsImportIMDbMovies)
                {
                    DataSource.ShowDrivesMoviesOnly = false;
                    DatabaseManager.Instance.ImportIMDbMovies(WaitScreen);
                }
                RegistryHelper.ProfileName = ProfileName;
                DataSource.SelectProfile(ProfileName);
                RegistryHelper.ScanOption = ScanOption;
                DataSource.UpdateTitles();
                Logger.Instance.Write("Profile creation successfull");
                return true;
            }
            return false;
        }

        private void SaveProfile()
        {
            Logger.Instance.Write("Saving Profile");
            if (!DatabaseManager.Instance.IsProfileExists(ProfileName))
            {
                DatabaseManager.Instance.CreateProfile(ProfileName);
            }
            RegistryHelper.ProfileName = ProfileName;
        }


        public ObservableCollection<ScannedDirectory> ScannedDirectories
        {
            get { return (ObservableCollection<ScannedDirectory>)GetValue(ScannedDirectoriesProperty); }
            set { SetValue(ScannedDirectoriesProperty, value); }
        }

        public static readonly DependencyProperty ScannedDirectoriesProperty =
            DependencyProperty.Register("ScannedDirectories", typeof(ObservableCollection<ScannedDirectory>), typeof(ProfileSelectorPresenter), new UIPropertyMetadata(null));



        public bool IsImportIMDbMovies
        {
            get { return (bool)GetValue(IsImportIMDbMoviesProperty); }
            set { SetValue(IsImportIMDbMoviesProperty, value); }
        }

        public static readonly DependencyProperty IsImportIMDbMoviesProperty =
            DependencyProperty.Register("IsImportIMDbMovies", typeof(bool), typeof(ProfileSelectorPresenter), new UIPropertyMetadata(true));

        
    }
}
